package cn.seocoo.platform.api.controller.common;

import cn.seocoo.platform.api.util.JSONResult;
import cn.seocoo.platform.api.util.StringEx;
import cn.seocoo.platform.base.dto.BaseCommonDto;
import cn.seocoo.platform.common.core.controller.BaseController;
import cn.seocoo.platform.common.utils.StringUtils;
import cn.seocoo.platform.sysArea.domain.SysArea;
import cn.seocoo.platform.sysArea.dto.SysAreaDto;
import cn.seocoo.platform.sysArea.service.ISysAreaService;
import cn.seocoo.platform.system.domain.SysDictData;
import cn.seocoo.platform.system.service.ISysDictDataService;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


@Api(value = "公共类接口", description = "公共类接口")
@RestController
@RequestMapping("/api/common")
public class  ApiCommonController extends BaseController {

    @Autowired
    private ISysAreaService iSysAreaService;

    @Autowired
    private ISysDictDataService dictDataService;


    /**
     * 支持图片的类型
     **/
    private String[] types = {".jpg", ".jpeg", ".png", ".PNG", ".JPG", ".JPEG"};
    /**
     * 图片保存路径
     **/
    @Value("${save.api.image.path}")
    private String saveImgPath;


    /**
     * 图片访问ip
     **/
    @Value("${visit.path}")
    private String visitPath;


    /**
     * 获取数组字典公共方法
     *
     * @param dataType 传入的数据字典类型
     * @author duanpj
     * @date: 2019/10/29 9:00
     */
    @GetMapping("/getDictValue")
    public JSONResult getDictValue(String dataType) {
        PageHelper.orderBy("dict_sort asc");
        List<SysDictData> objList = dictDataService.selectDictDataByType(dataType);
        List<BaseCommonDto> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(objList)) {
            for (SysDictData sysDictData : objList) {
                BaseCommonDto dto = new BaseCommonDto();
                dto.setId(sysDictData.getDictValue());
                dto.setText(sysDictData.getDictLabel());
                list.add(dto);
            }
        }
        return JSONResult.ok(list);
    }

    /**
     * 获取所有的34个省级行政区域
     *
     * @author duanpj
     * @date: 2019/8/20 16:16
     */
    @ApiOperation("获取所有的34个省级行政区域")
    @GetMapping("/getProvince")
    public JSONResult getProvince() {
        List<SysArea> proList = iSysAreaService.selectSysAreaByProvince(new SysArea());
        if (StringUtils.isNotEmpty(proList)) {
            List<SysAreaDto> dtoList = new ArrayList<>();
            for (SysArea sysArea : proList) {
                SysAreaDto dto = new SysAreaDto();
                dto.setId(sysArea.getId());
                dto.setAreaCode(sysArea.getCode());
                dto.setAreaAddress(sysArea.getProvince());
                dtoList.add(dto);
            }
            return JSONResult.ok(dtoList);
        } else {
            return JSONResult.ok("暂无数据");
        }
    }


    /**
     * 根据省code查询下级所有市区
     *
     * @param pcode 省级行政区code
     * @author duanpj
     * @date: 2019/11/8 10:51
     */
    @ApiOperation("根据省code查询下级所有市区")
    @GetMapping("/getCityByProvince")
    public JSONResult getCityByProvince(String pcode) {
        List<SysArea> cityList = iSysAreaService.SelectCityByProvince(pcode);
        if (StringUtils.isNotEmpty(cityList)) {
            List<SysAreaDto> dtoList = new ArrayList<>();
            for (SysArea sysArea : cityList) {
                SysAreaDto dto = new SysAreaDto();
                dto.setId(sysArea.getId());
                dto.setAreaCode(sysArea.getCode());
                dto.setAreaAddress(sysArea.getCity());
                dtoList.add(dto);
            }
            return JSONResult.ok(dtoList);
        } else {
            return JSONResult.ok("暂无数据");
        }
    }


    /**
     * 上传图片接口
     *
     * @param file
     * @return
     * @throws IOException
     * @author duanpj
     */
    @PostMapping("/ImgUpload")
    public JSONResult singleImgUpload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String fileName = "";
        String dbPath = "";
        if (file != null && !file.isEmpty()) {
            fileName = file.getOriginalFilename();
            //文件类型
            String type = fileName.substring(fileName.lastIndexOf("."));
            if (Arrays.asList(types).contains(type)) {
                FileOutputStream fileOutputStream = null;
                InputStream inputStream = null;
                try {
                    //源文件中文乱码导致图片链接指向不到,使用日期
                    Calendar cal = Calendar.getInstance();
                    fileName = StringEx.getRandomStringByDate(22) + type;
                    String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
                    dbPath = "/upload/" + late;
                    File fileSourcePath = new File(saveImgPath + dbPath);
                    if (!fileSourcePath.exists()) {
                        //目录不存在的情况下创建目录
                        fileSourcePath.mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                    dbPath += "/" + fileName;
                    logger.warn("----------------------->图片保存路径：" + dbPath);
                    Map map = new HashMap<>();
                    map.put("filePath", dbPath);
                    return JSONResult.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return JSONResult.errorMsg("上传图片异常");
                } finally {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
            }
            return JSONResult.errorMsg("不允许上传此类型文件");
        }
        return JSONResult.errorMsg("文件不能为空！");
    }

    /**
     * 富文本内容图片上传接口
     *
     * @author duanpj
     * @date: 2019/10/30 16:14
     */
    @PostMapping("/richtextImgUpload")
    public JSONResult richtextImgUpload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String fileName = "";
        String dbPath = "";
        if (file != null && !file.isEmpty()) {
            fileName = file.getOriginalFilename();
            //文件类型
            String type = fileName.substring(fileName.lastIndexOf("."));
            if (Arrays.asList(types).contains(type)) {
                InputStream inputStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    Calendar cal = Calendar.getInstance();
                    String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
                    fileName = StringEx.getRandomStringByDate(22) + type;
                    dbPath = "/upload/" + late;
                    File fileSourcePath = new File(saveImgPath + dbPath);
                    if (!fileSourcePath.exists()) {
                        //目录不存在的情况下创建目录
                        fileSourcePath.mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                    dbPath += "/" + fileName;
                    logger.warn("----------------------->富文本图片路径：" + visitPath + dbPath);
                    return JSONResult.ok(visitPath + dbPath);
                } catch (Exception e) {
                    e.printStackTrace();
                    return JSONResult.errorMsg("上传图片异常");
                } finally {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
            }
            return JSONResult.errorMsg("不允许上传此类型文件");
        }
        return JSONResult.errorMsg("文件不能为空！");
    }


    /**
     * 获取文件扩展名
     *
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 文件保存路径
     */
    @Value("${save.api.document.path}")
    private String saveDocumentPath;

    /**
     * @return cn.seocoo.platform.api.util.JSONResult
     * @Author L
     * @Description 不限类型上传
     * @Date 11:25 上午 2019/11/4
     * @Param [file]
     **/
    @PostMapping("/fileUpload")
    public JSONResult fileUpload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String fileName = "";
        String dbPath = "";
        if (file != null && !file.isEmpty()) {
            fileName = file.getOriginalFilename();
            //文件类型
            String type = fileName.substring(fileName.lastIndexOf("."));
            if (true) {
                FileOutputStream fileOutputStream = null;
                InputStream inputStream = null;
                try {
                    //源文件中文乱码导致图片链接指向不到,使用日期
                    Calendar cal = Calendar.getInstance();
                    fileName = StringEx.getRandomStringByDate(22) + type;
                    String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
                    dbPath = "/upload/" + late;
                    File fileSourcePath = new File(saveDocumentPath + dbPath);
                    if (!fileSourcePath.exists()) {
                        //目录不存在的情况下创建目录
                        fileSourcePath.mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
                    inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                    dbPath += "/" + fileName;
                    Map map = new HashMap<>();
                    map.put("filePath", dbPath);
                    map.put("fileName", fileName);
                    logger.warn("----------------------->文件保存路径：" + dbPath);
                    return JSONResult.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return JSONResult.errorMsg("上传文件异常");
                } finally {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                }
            }
            return JSONResult.errorMsg("不允许上传此类型文件");
        }
        return JSONResult.errorMsg("文件不能为空");
    }


}
